How can I avoid RuntimeError: dictionary changed size during iteration